package com.longchat.query;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.longchat.domain.permission.SysUser;
import com.longchat.dto.system.SysUserQueryInfo;

@Component
public class SysUserQuery {
	@PersistenceContext
	private EntityManager entityManager;
	
	public List<SysUser> findUsersBy(SysUserQueryInfo info){
		StringBuffer sql = new StringBuffer("select * from sysuser s where 1=1");
		if(!StringUtils.isEmpty(info.getName())){
			sql.append(" and s.name like :name");
		}
		if(!StringUtils.isEmpty(info.getUserName())){
			sql.append(" and s.user_name=:userName");
		}
		sql.append(" limit :start,:length");
		Query query = entityManager.createNativeQuery(sql.toString(), SysUser.class);
		if(!StringUtils.isEmpty(info.getName())){
			query.setParameter("name",info.getName());
		}
		if(!StringUtils.isEmpty(info.getUserName())){
			query.setParameter("userName","%"+info.getUserName()+"%");
		}
		query.setParameter("start", info.getStart());
		query.setParameter("length", info.getLength());
		return query.getResultList();
	}
	
	public Integer findUsersCountBy(SysUserQueryInfo info){
		StringBuffer sql = new StringBuffer("select count(1) from sysuser s where 1=1");
		if(!StringUtils.isEmpty(info.getName())){
			sql.append(" and s.name like :name");
		}
		if(!StringUtils.isEmpty(info.getUserName())){
			sql.append(" and s.user_name=:userName");
		}
		Query query = entityManager.createNativeQuery(sql.toString());
		if(!StringUtils.isEmpty(info.getName())){
			query.setParameter("name","%"+info.getName()+"%");
		}
		if(!StringUtils.isEmpty(info.getUserName())){
			query.setParameter("userName",info.getUserName());
		}
		String count = query.getSingleResult().toString();
		return Integer.parseInt(count);
	}
}
